package com.sunday.aomi.ui.mine.statistic;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.adapter.CommonAdapter;
import com.sunday.common.adapter.RecylerViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.pickerview.TimePickerView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.common.widgets.signcalendar.DateUtil;
import com.sunday.aomi.R;
import com.sunday.aomi.entity.SalesDetail;
import com.sunday.aomi.entity.SalesItem;
import com.sunday.aomi.http.ApiClient;
import com.sunday.aomi.utils.DateUtils;
import com.sunday.member.entity.order.OrderItem;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/6/12.
 */

public class TotalProfitListActivity extends BaseActivity {

    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.start_time)
    TextView start_Time;
    @Bind(R.id.end_time)
    TextView end_Time;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.total_money)
    TextView totalMoney;

    private int type;
    private String allMoney;
    private List<SalesItem> dataSet = new ArrayList<>();
    private CommonAdapter<SalesItem> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_total_profit_list);
        ButterKnife.bind(this);
        Date date = new Date();
        endTime = DateUtils.dateToStr(date);
        end_Time.setText(endTime);
        end = date;
        type = getIntent().getIntExtra("type", 1);//1:采购明细 2：销售明细
        if (type == 1) {
            title.setText("采购总额");
            start = DateUtils.getLastMonthDay();
            startTime = DateUtils.dateToStr(start);
            start_Time.setText(startTime);
            getData();
        } else {
            title.setText("总营业额");
            start = DateUtils.getYesterDay();
            startTime = DateUtils.dateToStr(start);
            start_Time.setText(startTime);

            getData();
        }

        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        totalMoney.setText(SpannalbeStringUtils.setTextColor("合计:", mContext.getResources().getColor(R.color.black_3)));
        totalMoney.append(SpannalbeStringUtils.setTextColor("￥0.00", mContext.getResources().getColor(R.color.price_yellow)));
        initRecyclerView();
    }

    private boolean isCanloadMore;
    private int lastVisibleItem;
    private LinearLayoutManager layoutManager;

    private void initRecyclerView() {
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).drawable(R.drawable.shape_divider).build());
        adapter = new CommonAdapter<SalesItem>(mContext, R.layout.item_order_statistic, dataSet) {
            @Override
            public void convert(RecylerViewHolder holder, SalesItem orderItem) {
                bind(holder, orderItem);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        pageNo=1;
                getData();
            }
        });

    }

    private void bind(RecylerViewHolder holder, SalesItem orderItem) {
        switch (type) {
            case 1:
                ((TextView) holder.getView(R.id.text1)).setText(String.format("%.2f", orderItem.getPayAmount()));
                ((TextView) holder.getView(R.id.text1)).setTextColor(mContext.getResources().getColor(R.color.price_yellow));
                ((TextView) holder.getView(R.id.text3)).setText(String.format("订单号：\n%s", orderItem.getOrderNo()));
                ((TextView) holder.getView(R.id.text2)).setText("支付");
                ((TextView) holder.getView(R.id.text4)).setText(String.format("%s", orderItem.getCreateTime()));

                break;
            case 2:
                ((TextView) holder.getView(R.id.text1)).setText(String.format("%.2f", orderItem.getPayAmount()));
                ((TextView) holder.getView(R.id.text3)).setText(String.format("订单号：\n%s", orderItem.getOrderNo()));
                ((TextView) holder.getView(R.id.text2)).setText(orderItem.getMemberName());
                ((TextView) holder.getView(R.id.text4)).setText(String.format("%s", orderItem.getCreateTime()));
                break;
        }

    }


    private TimePickerView timePickerView;
    private boolean isStart;//是否选择开始时间
    private Date start, end;
    private String startTime, endTime;
    private int pageNo = 1;
    private int pageSize = 10;

    @OnClick({R.id.start_time, R.id.end_time})
    void onClick(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.start_time:
                isStart = true;
                break;
            case R.id.end_time:
                isStart = false;
                break;
        }
        timePickerView = new TimePickerView(mContext, TimePickerView.Type.YEAR_MONTH_DAY);
        timePickerView.setTime(new Date());
        timePickerView.setCyclic(true);
        timePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
                if (isStart) {
                    startTime = sdf.format(date);
                    start = date;
                    if (!TextUtils.isEmpty(endTime) && !DateUtils.compareDate(start, end)) {
                        ToastUtils.showToast(mContext, "请选择正确时间段");
                    } else if (!TextUtils.isEmpty(endTime) && DateUtils.compareDate(start, end)) {
                        start_Time.setText(startTime);
                        getData();
                        timePickerView.dismiss();
                    } else {
                        start_Time.setText(startTime);
                        timePickerView.dismiss();
                    }
                } else {
                    endTime = sdf.format(date);
                    end = date;
                    if (!TextUtils.isEmpty(startTime) && !DateUtils.compareDate(start, end)) {
                        ToastUtils.showToast(mContext, "请选择正确时间段");

                    } else if (!TextUtils.isEmpty(startTime) && DateUtils.compareDate(start, end)) {
                        timePickerView.dismiss();
                        end_Time.setText(endTime);
                        getData();
                    } else {
                        end_Time.setText(endTime);
                        timePickerView.dismiss();
                    }
                }

            }
        });
        timePickerView.show();
    }


    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"type", "createTime_start", "createTime_end", "pageSize", "pageNumber", "nonce"};
        String[] str2 = new String[]{String.valueOf(type), startTime, endTime, String.valueOf(pageNo), "10", nonce};
        showLoadingDialog(0);
        Call<ResultDO<SalesDetail>> call = ApiClient.getApiAdapter().getRevenueDetail(type, startTime, endTime,
                pageSize, pageNo, null, null, nonce,
                SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<SalesDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<SalesDetail>> call, Response<ResultDO<SalesDetail>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    if (response.body().getResult().getDatas() != null)
                        dataSet.addAll(response.body().getResult().getDatas());
                    allMoney = response.body().getResult().getTotalAmount();
                    totalMoney.setText(SpannalbeStringUtils.setTextColor("合计:", mContext.getResources().getColor(R.color.black_3)));
                    totalMoney.append(SpannalbeStringUtils.setTextColor("￥" + allMoney, mContext.getResources().getColor(R.color.price_yellow)));
                    if (response.body().getResult().getDatas().size() == 10) {
                        isCanloadMore = true;
                        pageNo++;
                    } else {
                        isCanloadMore = false;
                    }
                    if (dataSet.size() > 0) {
                        emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        totalMoney.setVisibility(View.VISIBLE);
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NODATA);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<SalesDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }


}
